<?php

namespace App\Services;

use App\Models\BookOrder;
use App\Models\BookRule;
use App\Models\Child;
use App\Models\User;
use App\Models\UserRole;

/**
 * Class BookOrderService
 * @package App\Services
 * @author zjw
 * 订单服务
 */
class BookOrderService
{
    /**
     * @param $user
     * @param BookRule $rule
     * @param int $isAuto
     * @param string $type
     * @param int $childrenId
     * @return mixed
     */
    public static function generateOrder($user, BookRule $rule, $isAuto = 0, $type = BookOrder::TYPE_NORMAL, $childrenId = 0)
    {
          return BookOrder::create([
              'user_id' => $user->id,
              'book_rule_id' => $rule->id,
              'is_auto' => $isAuto,
              'school_id' => $user->school_id,
              'eat_name' => $type === BookOrder::TYPE_CHILDREN ? Child::query()->find($childrenId)->name : $user->name,
              'eat_phone' => $user->phone,
              'type' => $type,
              'children_id' => $childrenId
          ]);
    }

    /**
     * @param $user
     * @param BookRule $bookRule
     * @param $childrenId
     * @return mixed
     * 子女订单
     */
    public static function generateChildrenOrder($user, BookRule $bookRule, $childrenId)
    {
        return static::generateOrder($user, $bookRule, 0, BookOrder::TYPE_CHILDREN, $childrenId);
    }

    /**
     * @param $user
     * @param BookRule $bookRule
     * @param $childrenId
     * @return mixed
     * 自动加单子女订单
     */
    public static function generateAutoChildrenOrder($user, BookRule $bookRule, $childrenId)
    {
        return static::generateOrder($user, $bookRule, 1, BookOrder::TYPE_CHILDREN, $childrenId);
    }

    /**
     * @param $user
     * @param BookRule $bookRule
     * @return mixed
     */
    public static function generateOfficialOrder($user, BookRule $bookRule)
    {
        return static::generateOrder($user, $bookRule, 0, BookOrder::TYPE_OFFICIAL);
    }

    /**
     * @param User $user
     * @param BookRule $bookRule
     * @param $num
     * @return bool
     */
    public static function generateAdditionOrder($user, BookRule $bookRule,$num)
    {
        for($i = 1; $i <= $num; $i++) {
            static::generateOrder($user, $bookRule, 0, BookOrder::TYPE_ADDITION );
        }
        return true;
    }

    /**
     * @param User $user
     * @param BookRule $bookRule
     * @return bool
     * 新增订餐规则时自动生成订单
     */
    public static function generateAutoOrder(User $user, BookRule $bookRule)
    {
        return static::generateOrder($user, $bookRule, 1, BookOrder::TYPE_NORMAL);
    }

    /**
     * @param BookOrder $bookOrder
     * @return BookOrder|bool
     * 制作订单
     */
    public static function making(BookOrder $bookOrder)
    {
        if ($bookOrder->status === BookOrder::ORDER_STATUS_INIT) {
            $bookOrder->status = BookOrder::ORDER_STATUS_MAKING;
            $bookOrder->making_at = now()->format("Y-m-d H:i:s");
            $bookOrder->save();
            return $bookOrder;
        }
        return false;
    }

    /**
     * @param BookOrder $bookOrder
     * @return BookOrder|bool
     * 完成订单
     */
    public static function finished(BookOrder $bookOrder)
    {
        if($bookOrder->status === BookOrder::ORDER_STATUS_MAKING){
            $bookOrder->status = BookOrder::ORDER_STATUS_COMPLETED;
            $bookOrder->finished_at = now()->format("Y-m-d H:i:s");
            $bookOrder->save();

            return $bookOrder;
        }
        return false;
    }

    /**
     * @param BookOrder $bookOrder
     * @return BookOrder|bool
     * 学校后台取消订单
     */
    public static function backendCancel(BookOrder $bookOrder)
    {
        if ($bookOrder->status != BookOrder::ORDER_STATUS_CANCELED && $bookOrder->is_calculated == BookOrder::NOT_CALCULATED) {
            $bookOrder->status = BookOrder::ORDER_STATUS_CANCELED;
            $bookOrder->canceled_at = now()->format("Y-m-d H:i:s");
            $bookOrder->save();
            return $bookOrder;
        }
        return false;
    }

    /**
     * @param BookOrder $bookOrder
     * @param $originPrice
     * @param $eatType
     * @return bool
     * 结算当前订单
     * 订单状态为normal，正常结算
     * 订单状态为addition或children时，按订单原价结算
     */
    public static function settle(BookOrder $bookOrder, $originPrice, $eatType)
    {
        // 1.标记此订餐规则下的所有订单为已计算餐费
        $bookOrder->is_calculated = BookOrder::CALCULATED;
        // 2.填充每笔订单的原价为 条目总价 / 订单数
        $bookOrder->origin_price = $originPrice;
        if ($bookOrder->type === BookOrder::TYPE_NORMAL) {
            // 正常结算订单
            // 订单的计费规则 = 当前应用的订餐规则下的订餐类型若是早餐，则去找对应订单的用户角色表中的早餐计费规则
            if ($eatType === BookRule::EAT_TYPE_BREAKFAST) {
                $priceRule = $bookOrder->user->role->morning_price_rule;        // 早餐计费规则
                $payPrice = $bookOrder->user->role->morning_price;              // 固定早餐费用
                $rate = $bookOrder->user->role->breakfast_rate;                 // 计费早餐付款比例
            }
            if ($eatType === BookRule::EAT_TYPE_LUNCH) {
                $priceRule = $bookOrder->user->role->lunch_price_rule;
                $payPrice = $bookOrder->user->role->lunch_price;
                $rate = $bookOrder->user->role->lunch_rate;
            }
            if ($eatType === BookRule::EAT_TYPE_DINNER) {
                $priceRule = $bookOrder->user->role->dinner_price_rule;
                $payPrice = $bookOrder->user->role->dinner_price;
                $rate = $bookOrder->user->role->dinner_rate;
            }
            // 3.填充每笔订单的计费规则
            $bookOrder->price_rule = $priceRule;
            //4.订单实际支付价格
            // 4.1若为固定餐标，则实际支付 = user_role表中的固定餐费
            if ($bookOrder->price_rule === UserRole::FIXED_MEAL_MARK) {
                $bookOrder->pay_price = $payPrice;
            }
            // 4.2若为计算餐标，则实际支付 = 原价 * 付款比例（早、中、晚）
            if ($bookOrder->price_rule === UserRole::CHARGING_MEAL_MARK) {
                $bookOrder->pay_price = (float)bcdiv($originPrice * $rate, '100', 2);
            }
        } else {
            // 原价结算订单
            // 3.填充每笔订单的计费规则
            $bookOrder->price_rule = UserRole::ADDITION_MEAL_MARK;
            // 4.订单实际支付价格
            // 4.1全额支付
            $bookOrder->pay_price = $originPrice;
        }
        return $bookOrder->save();
    }
}
